<template>
  <div class="home">
    <transition-loading :isShow="loadShow" />
    <ParticleBackground />
    <div class="chart-list">
      <home-header :select-options="selectOptions" :plan="selectValue" @init-screen="getInitData" />
      <div style="padding: 0 12px" class="chart-content">
        <!-- 整体布局 左 中 右 -->
        <a-row :gutter="[12, 12]" class="chart-content-row">
          <!-- 左侧 -->
          <a-col v-bind="leftRightCol" class="chart-content-col">
            <a-row class="chart-content-left">
              <a-col class="chart-content-left-item" :span="24">
                <ModuleItem title="情感占比" :loading="sentimentLoading">
                  <div
                    v-if="sentimentData.length || sentimentLoading"
                    :ref="attentChart.container"
                    class="chart-container"
                  ></div>
                  <a-empty v-else style="margin-top: 24px">
                    <template #description>
                      <span style="color: #ffffff">暂无数据</span>
                    </template>
                  </a-empty>
                </ModuleItem>
              </a-col>
              <a-col class="chart-content-left-item" :span="24">
                <ModuleItem title="高频词分布统计" :loading="keywordIndexTrendLoading">
                  <div style="width: 94%; height: 92%; margin: 12px auto">
                    <div :ref="wordCloud.container" class="chart-word-container"></div>
                  </div>
                </ModuleItem>
              </a-col>
              <a-col class="chart-content-left-item" :span="24">
                <ModuleItem title="方案命中关键词" :loading="matchedKeywordsLoading">
                  <div
                    v-if="matchedKeywordsData[0]?.data?.length || matchedKeywordsLoading"
                    :ref="openRankChart.container"
                    class="chart-container"
                  ></div>
                  <a-empty v-else style="margin-top: 24px">
                    <template #description>
                      <span style="color: #ffffff">暂无数据</span>
                    </template>
                  </a-empty>
                </ModuleItem>
              </a-col>
            </a-row>
          </a-col>
          <!-- 中间 -->
          <a-col v-bind="centerCol" class="chart-content-col">
            <a-row class="chart-content-center">
              <a-col class="chart-content-center-item" :span="24">
                <ModuleItem :loading="keywordCloudLoading">
                  <div class="index-data">
                    <index-num :overview-data="overViewData" />
                    <div style="display: flex; justify-content: center">
                      <RotateContent />
                    </div>
                    <!-- <div
                      v-if="keywordIndexTrendData.length || keywordIndexTrendLoading"
                      :ref="keywordIndexTrendChart.container"
                      class="chart-container"
                    ></div>
                    <a-empty v-else style="margin-top: 24px">
                      <template #description>
                        <span style="color: #ffffff">暂无数据</span>
                      </template>
                    </a-empty> -->
                  </div>
                </ModuleItem>
              </a-col>
              <a-col class="chart-content-center-item" :span="24">
                <ModuleItem title="热度排名" :loading="indexTrendLoading">
                  <div v-if="indexTrendData.length || indexTrendLoading" class="virtual-list-content">
                    <list-header :titleList="titleList" />
                    <new-virtual-list :data-source="indexTrendData" :loading="indexTrendLoading" class="virtual-list">
                      <template #item="{ item }">
                        <a-tooltip placement="top" color="rgba(73, 146, 255, 0.8)">
                          <template #title>
                            <div>标题：{{ item.content_title }}</div>
                            <span>描述：{{ item.content_desc }}</span>
                          </template>
                          <div class="virtual-list-item">
                            <span class="virtual-list-item-col">{{ item.content_title }}</span>
                            <span class="virtual-list-item-col">{{ item.heat_score }}</span>
                            <span class="virtual-list-item-col">
                              <span v-if="item.sentiment_polarity === 'positive'">积极</span>
                              <span v-else-if="item.sentiment_polarity === 'neutral'">中性</span>
                              <span v-else>消极</span>
                            </span>
                            <span class="virtual-list-item-col">{{ item.content_desc }}</span>
                            <span class="virtual-list-item-col">{{ item.event_time }}</span>
                          </div>
                        </a-tooltip>
                      </template>
                    </new-virtual-list>
                  </div>
                  <a-empty v-else style="margin-top: 24px">
                    <template #description>
                      <span style="color: #ffffff">暂无数据</span>
                    </template>
                  </a-empty>
                </ModuleItem>
              </a-col>
            </a-row>
          </a-col>
          <!-- 右侧 -->
          <a-col v-bind="leftRightCol" class="chart-content-col">
            <a-row class="chart-content-right">
              <a-col class="chart-content-right-item" :span="24">
                <ModuleItem title="情感分析走势图" :loading="sentimentTrandLoading">
                  <div
                    v-if="sentimentTrandData.length || sentimentTrandLoading"
                    :ref="emotionAnalysisChart.container"
                    class="chart-container"
                  ></div>
                  <a-empty v-else style="margin-top: 24px">
                    <template #description>
                      <span style="color: #ffffff">暂无数据</span>
                    </template>
                  </a-empty>
                </ModuleItem>
              </a-col>
              <a-col class="chart-content-right-item" :span="24">
                <ModuleItem title="平台活跃度" :loading="platformActivityLoading">
                  <div
                    v-if="platformActivityData.length || platformActivityLoading"
                    :ref="platformActivityChart.container"
                    class="chart-container"
                  ></div>
                  <a-empty v-else style="margin-top: 24px">
                    <template #description>
                      <span style="color: #ffffff">暂无数据</span>
                    </template>
                  </a-empty>
                </ModuleItem>
              </a-col>
              <a-col class="chart-content-right-item" :span="24">
                <ModuleItem title="最新内容" :loading="contentLatestLoading">
                  <LastContent v-if="contentLatestData.length" :data-source="contentLatestData" />
                  <a-empty v-else style="margin-top: 24px">
                    <template #description>
                      <span style="color: #ffffff">暂无数据</span>
                    </template>
                  </a-empty>
                </ModuleItem>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
        <!-- 背景地球 -->
        <!-- <earth-bg /> -->
      </div>
    </div>
  </div>
  <!-- 弹窗 -->
  <chart-modal
    v-model:visible="chartModalData.visible"
    :type="chartModalData.type"
    :defaultValue="chartModalData.selectValue"
  />
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { debounce } from 'lodash';

import indexImg from '@/assets/images/index-bg.png';
import centerImg from '@/assets/images/center.png';
import headerImg from '@/assets/images/home-header.png';
import mapImg from '@/assets/images/map.png';
import lbxImg from '@/assets/images/lbx.png';
import jtImg from '@/assets/images/jt.png';

import HomeHeader from './components/home-header/index.vue';
import EarthBg from './components/earth-bg/index.vue';
import ChartModal from './components/chart-modal/index.vue';
import ListHeader from './components/list-header/index.vue';
import IndexNum from './components/index-num/index.vue';
import ParticleBackground from './components/particle-background/index.vue';
import LastContent from './components/last-content/index.vue';

import useOpenRank from './composables/use-open-rank';
import useReviewEfficient from './composables/use-review-efficient';
import useChartModal from './composables/use-chart-modal';
import useRadar from './composables/use-radar';
import useWordCloud from './composables/use-word-cloud';
import useBarLine from './composables/use-bar';
import useLine from './composables/use-line';
import usePie from './composables/use-pie';
import useTwoBarRate from './composables/use-two-bar-rate';
import RotateContent from './components/rotate-content/index.vue';

import { titleList, leftRightCol, centerCol } from './config';

import {
  fetchContentOverview,
  fetchSentimentRatio,
  fetchTopMatchedKeywords,
  fetchSentimentTrand,
  fetchContentTop,
  fetchKeywordCloud,
  fetchKeywordIndexTrend,
  fetchPlatformActivity,
  fetchContentLatest,
  fetchGetAllPlan
} from '@/service/home';

const chartModalData = useChartModal();
const projectChart = useOpenRank({ showHandler: chartModalData.changeVisible, type: 5 });
const reviewEfficient = useReviewEfficient(chartModalData.changeVisible);
const radarFirst = useRadar();
const wordCloud = useWordCloud();
const openRankChart = useBarLine();
const attentChart = usePie();
const emotionAnalysisChart = useLine();
const platformActivityChart = usePie();
const keywordIndexTrendChart = useTwoBarRate();

/**
 * @description 处理全部图表的缩放
 */
const chartResize = debounce(() => {
  openRankChart.chart.resizeChart();
  reviewEfficient.chart.resizeChart();
  radarFirst.chart.resizeChart();
  attentChart.chart.resizeChart();
  projectChart.chart.resizeChart();
  wordCloud.chart.resizeChart();
  emotionAnalysisChart.chart.resizeChart();
  platformActivityChart.chart.resizeChart();
  keywordIndexTrendChart.chart.resizeChart();
}, 300);

const selectOptions = [
  {
    label: '方案1',
    value: '1'
  },
  {
    label: '方案2',
    value: '2'
  }
];
const getPlanOptions = async () => {
  const planOptions = await fetchGetAllPlan();
  console.log('所有方案列表', planOptions);
};

const selectValue = ref('1');

const loadShow = ref<boolean>(true);
const imgCount = 6;
let curCount = 0;
const addImgCount = () => {
  curCount++;
  if (curCount === imgCount) {
    loadShow.value = false;
  }
};

const loadImg = () => {
  const imgArr = [indexImg, centerImg, headerImg, mapImg, lbxImg, jtImg];
  imgArr.forEach(item => {
    const newImage = new Image();
    newImage.src = item;
    newImage.onload = () => {
      addImgCount();
    };
  });
};

const planId = ref('1');
const period = ref('15d');

// 数据概览
const overViewData = ref({
  negative_count: {
    count: 0,
    percentage: 0
  },
  positive_or_neutral: {
    count: 0,
    percentage: 0
  },
  total: 0
});
const getOverView = async () => {
  const result: any = await fetchContentOverview({ plan_id: planId.value, period: period.value });
  overViewData.value = result.data;
};

// 情感占比
const sentimentLoading = ref(false);
const sentimentData = ref<any[]>([]);
const getSentimentRatio = async () => {
  sentimentLoading.value = true;
  sentimentData.value = [];
  const result: any = await fetchSentimentRatio({ plan_id: planId.value, period: period.value });
  sentimentLoading.value = false;
  if (result?.data) {
    sentimentData.value.push({
      name: '负面',
      value: result.data?.negative?.count || 0
    });
    sentimentData.value.push({
      name: '中性',
      value: result.data?.neutral?.count || 0
    });
    sentimentData.value.push({
      name: '正面',
      value: result.data?.positive?.count || 0
    });
    attentChart.chart.initChart(sentimentData.value);
  }
};

// 方案命中关键词
const matchedKeywordsLoading = ref(false);
const matchedKeywordsData = ref<any[]>([]);
const getTopMatchedKeywords = async () => {
  matchedKeywordsLoading.value = true;
  const result: any = await fetchTopMatchedKeywords({ plan_id: planId.value, period: period.value });
  matchedKeywordsData.value = [
    {
      name: '关键词',
      type: 'bar',
      data: []
    }
  ];
  if (result?.data?.length) {
    result.data.forEach((item: any) => {
      matchedKeywordsData.value[0].data.push({
        name: item.matched_keyword,
        value: item.total_count
      });
    });
  } else {
    matchedKeywordsData.value[0].data = [];
  }
  openRankChart.chart.initChart(matchedKeywordsData.value);
  matchedKeywordsLoading.value = false;
};

// 情感走势（敏感/非敏感）
const sentimentTrandLoading = ref(false);
const sentimentTrandData = ref<any[]>([]);
const getSentimentTrand = async () => {
  sentimentTrandLoading.value = true;
  const result: any = await fetchSentimentTrand({ plan_id: planId.value, period: period.value });
  sentimentTrandData.value = [
    {
      name: '敏感',
      type: 'line',
      itemStyle: {
        color: '#4992ff'
      },
      data: []
    },
    {
      name: '非敏感',
      type: 'line',
      itemStyle: {
        color: '#eed15d'
      },
      data: []
    }
  ];
  if (result.data) {
    const sensitive: any = [];
    const nonSensitive: any = [];
    result.data?.time.forEach((item: any, index: number) => {
      sensitive.push({
        name: item,
        value: result.data.sensitive[index]
      });
      nonSensitive.push({
        name: item,
        value: result.data.non_sensitive[index]
      });
    });
    sentimentTrandData.value[0].data = sensitive;
    sentimentTrandData.value[1].data = nonSensitive;
  } else {
    sentimentTrandData.value = [];
  }
  emotionAnalysisChart.chart.initChart(sentimentTrandData.value);
  sentimentTrandLoading.value = false;
};

// 热度排名
const indexTrendData = ref<any[]>([]);
const indexTrendLoading = ref(false);
const getContentTop = async () => {
  indexTrendLoading.value = true;
  indexTrendData.value = [];
  const result: any = await fetchContentTop({ plan_id: planId.value, period: period.value });
  console.log('人多', result)
  indexTrendLoading.value = false;
  if (!result.error && result.data?.length) {
    indexTrendData.value = result.data;
  }
};

// 高频词分布统计
const keywordCloudData = ref<any[]>([]);
const keywordCloudLoading = ref(false);
const getKeywordCloud = async () => {
  try {
    keywordCloudLoading.value = true;
    const result: any = await fetchKeywordCloud({ plan_id: planId.value, period: period.value });
    keywordCloudLoading.value = false;
    keywordCloudData.value = [];
    if (result?.data.length) {
      result.data.forEach((item: any) => {
        keywordCloudData.value.push({
          name: item.keyword,
          value: item.count,
          percentage: item.percentage
        });
      });
    } else {
      keywordCloudData.value = [];
    }
    wordCloud.chart.initChart(keywordCloudData.value);
  } catch {
    keywordCloudLoading.value = false;
  }
};

// 高频词指数
const keywordIndexTrendData = ref<any[]>([]);
const keywordIndexTrendLoading = ref(false);
const getKeywordIndexTrend = async () => {
  keywordIndexTrendLoading.value = true;
  const result: any = await fetchKeywordIndexTrend({ plan_id: planId.value, period: period.value });
  keywordIndexTrendLoading.value = false;
  const categories: any[] = [];
  const countOne: any[] = [];
  const countTwo: any[] = [];
  const ratioData: any[] = [];
  let countThree: any[] = [];
  let maxNum = 0;
  if (result?.data?.length) {
    result.data.forEach((item: any, index: number) => {
      if (index < 6) {
        if (item.count_t0 > maxNum) {
          maxNum = item.count_t0;
        }
        if (item.count_t1 > maxNum) {
          maxNum = item.count_t1;
        }
        categories.push(item.sentiment_keyword);
        countOne.push(item.count_t0);
        countTwo.push(item.count_t1);
        ratioData.push(item.ratio);
      }
    });
    keywordIndexTrendData.value = result.data;
  }
  countThree = countTwo.map(() => maxNum + 1);
  keywordIndexTrendChart.chart.initChart({
    categories,
    countOne,
    countTwo,
    ratioData,
    countThree
  });
};

// 平台活跃度
const platformActivityData = ref<any[]>([]);
const platformActivityLoading = ref(false);
const getPlatformActivity = async () => {
  platformActivityLoading.value = true;
  const result: any = await fetchPlatformActivity({ plan_id: planId.value, period: period.value });
  platformActivityData.value = [];
  if (result?.data?.length) {
    result.data.forEach((item: any) => {
      platformActivityData.value.push({
        name: item.platform_name,
        value: item.total_count
      });
    });
  } else {
    platformActivityData.value = [];
  }
  platformActivityChart.chart.initChart(platformActivityData.value);
  platformActivityLoading.value = false;
};

// 最新内容
const contentLatestData = ref<any[]>([]);
const contentLatestLoading = ref(true);
const getContentLatest = async () => {
  contentLatestLoading.value = true;
  const result: any = await fetchContentLatest({ plan_id: planId.value, period: period.value, top_n: 9 });
  if (!result.error && result.data?.length) {
    contentLatestData.value = result.data;
  } else {
    contentLatestData.value = [];
  }
  contentLatestLoading.value = false;
};

const getInitData = async (item?: { planId: string; period: string }) => {
  if (item) {
    planId.value = item.planId;
    period.value = item.period;
  }
  getContentLatest();
  getContentTop();
  getOverView();
  getSentimentRatio();
  getTopMatchedKeywords();
  getSentimentTrand();
  getKeywordCloud();
  getKeywordIndexTrend();
  getPlatformActivity();
};

onMounted(async () => {
  loadImg();
  await getPlanOptions();
  getInitData();
  window.addEventListener('resize', chartResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', chartResize);
});
</script>

<style lang="scss" scoped>
.home {
  position: relative;
  width: 100%;
  height: 100%;
  // background: url('@/assets/images/index-bg.png') no-repeat;
  // background: linear-gradient(135deg, #0c1e3a 0%, #1a237e 50%, #0c1e3a 100%);
  background: linear-gradient(135deg, #041c52 0%, #080924 50%, #060c22 100%);
  background-size: 100% 100%;

  .chart-list {
    height: 100%;

    .chart-content {
      height: calc(100% - 88px);
      margin-top: 12px;

      .chart-content-row,
      .chart-content-col {
        height: 100%;
      }

      .chart-container {
        width: 100%;
        height: 100%;
      }

      .chart-word-container {
        width: 100%;
        height: 96%;
        background-color: rgba(255, 255, 255, 0.5);
        padding: 16px;
        border-radius: 6px;
      }

      .virtual-list-content {
        display: flex;
        flex-direction: column;
        height: 100%;
        padding: 0 8px;

        .virtual-list-item {
          display: flex;
          gap: 8px;
          align-items: center;
          padding: 4px;
          color: rgb(255 255 255);
          cursor: pointer;

          &:hover {
            color: #4ccbf5;
            background: rgb(255 255 255 / 20%);
            border-radius: 4px;
          }

          &-col {
            width: 10%;
            overflow: hidden;
            text-align: center;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          &-col:nth-child(1) {
            width: 25%;
            text-align: left;
          }

          &-col:nth-child(4) {
            width: 30%;
          }

          &-col:nth-child(5) {
            width: 25%;
          }
        }

        .virtual-index-trend-list-item {
          display: flex;
          gap: 8px;
          align-items: center;
          padding: 4px;
          color: rgb(255 255 255);
          cursor: pointer;

          &:hover {
            color: #4ccbf5;
            background: rgb(255 255 255 / 20%);
            border-radius: 4px;
          }

          &-col {
            overflow: hidden;
            text-align: center;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          &-col:nth-child(1) {
            text-align: center;
            width: 30%;
          }

          &-col:nth-child(2) {
            text-align: center;
            width: 15%;
          }

          &-col:nth-child(3) {
            text-align: center;
            width: 30%;
          }

          &-col:nth-child(4) {
            text-align: center;
            width: 25%;
          }
        }
      }

      &-left {
        flex-direction: column;
        row-gap: 12px !important;
        height: 100%;

        &-item {
          flex: 1;
        }
      }

      &-center {
        flex-direction: column;
        row-gap: 12px !important;
        height: 100%;

        &-item:nth-child(1) {
          flex: 2.01;

          .index-data {
            display: flex;
            flex-direction: column;
            height: 100%;
            margin: 0 16px;
          }
        }

        &-item:nth-child(2) {
          flex: 0.99;
        }
      }

      &-right {
        flex-direction: column;
        row-gap: 12px !important;
        height: 100%;

        &-item {
          flex: 1;
        }
      }
    }
  }
}

// 小屏幕下的样式
@media (max-width: 576px) {
  .home {
    height: unset;
    background: #060c20;

    .chart-content {
      .chart-content-col:first-child {
        height: 1000px !important;
      }

      &-left,
      &-center {
        &-item {
          flex: 1 !important;
        }
      }

      .chart-content-col:nth-child(2) {
        height: 1500px !important;
      }

      .chart-content-col:nth-child(3) {
        height: 1500px !important;
      }
    }
  }
}
</style>

<style lang="scss">
.ant-tooltip-inner {
  min-height: unset;
}

.tooltip-review {
  // width: 80%;
  overflow: hidden;

  .tooltip-title {
    width: 180px;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .tooltip-btn {
    width: max-content;
    padding: 2px 5px;
    margin: 5px 5px 0 0;
    color: #ffffff;
    cursor: pointer;
    background-color: #ff6e76;
    border-radius: 4px;
  }

  .tooltip-item {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }

  .tooltip-label-icon {
    display: flex;
    align-items: center;
    margin-right: 5px;
    overflow: hidden;

    .tooltip-label {
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .tooltip-icon {
      width: 6px;
      height: 6px;
      margin-right: 5px;
      border-radius: 50%;
    }
  }

  .tooltip-value {
    flex: 1;
    flex-shrink: 0;
    font-size: 15px;
    font-weight: bold;
    color: #666666;
  }
}
</style>
